package com.techshine.util;

import java.math.BigDecimal;

public class DoubleUtil {
	 public static double sum(double d1,double d2,int scale){//+
	        BigDecimal bd1 = new BigDecimal(Double.toString(d1));
	        BigDecimal bd2 = new BigDecimal(Double.toString(d2));
	        return bd1.add(bd2).setScale(scale,BigDecimal.ROUND_HALF_UP).doubleValue();
	    }
	 public static double sub(double d1,double d2,int scale){//-
	        BigDecimal bd1 = new BigDecimal(Double.toString(d1));
	        BigDecimal bd2 = new BigDecimal(Double.toString(d2));
	        return bd1.subtract(bd2).setScale(scale,BigDecimal.ROUND_HALF_UP).doubleValue();
	    }
	 public static double mul(double d1,double d2,int scale){//*
	        BigDecimal bd1 = new BigDecimal(Double.toString(d1));
	        BigDecimal bd2 = new BigDecimal(Double.toString(d2));
	        return bd1.multiply(bd2).setScale(scale,BigDecimal.ROUND_HALF_UP).doubleValue();
	    }
	 public static double div(double d1,double d2,int scale) {
	        if ( d2 ==0d){
	          //  throw new Exception("分母不能为0");
	        }
	        BigDecimal bd1 = new BigDecimal(Double.toString(d1));
	        BigDecimal bd2 = new BigDecimal(Double.toString(d2));
	        return bd1.divide(bd2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
	    }
	 //double 转 string 去掉后面锝0
	 public static String getString(double i){
	        String s = String.valueOf(i);
	        if(s.indexOf(".") > 0){
	            //正则表达
	            s = s.replaceAll("0+?$", "");//去掉后面无用的零
	            s = s.replaceAll("[.]$", "");//如小数点后面全是零则去掉小数点
	        }
	        return s;
	    }
	 //数字转换为千位符


	 public static String numberToBits(String number){
	        String begin="";
	        String end="";
	        String[] num=number.split("\\.");
	        if(num.length>1){
	            begin=num[0];
	            end=num[1];
	        }else{
	            begin=number;
	        }
	        return begin.replaceAll("(?<=\\d)(?=(?:\\d{3})+$)", ",")+"."+end;
	    }


}
